#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>

#define THRNUM	4

//参数结构体
struct thr_arg_st
{
	int n;
};
//初始化互斥量
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//初始化条件变量
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
//全局变量num
static int num = 0;

//next小函数
int next(int n)
{
	if(n == THRNUM - 1)
		return 0;
	return n + 1;
}
//线程处理函数
static void * thr_func(void * p)
{
	int n = ((struct thr_arg_st *)p)->n;
	int c = 'a' + n;
	while(1)
	{
		pthread_mutex_lock(&mutex);				//上锁
		while(num != n)
		{
			pthread_cond_wait(&cond, &mutex);	//等待
		}
		write(1, &c, 1);						//输出
		num = next(num);						//写入下一个值
		pthread_cond_broadcast(&cond);			//唤醒所有人
		pthread_mutex_unlock(&mutex);			//解锁
	}
	pthread_exit(p);
}
int main()
{
	pthread_t tid[THRNUM];
	int i, err;
	struct thr_arg_st * p;
	void * ptr_to_free;

	//创建线程
	for(i = 0; i < THRNUM; i++)
	{
		//为参数申请空间
		p = malloc(sizeof(*p));
		if(p == NULL)
		{
			perror("malloc");
			exit(1);
		}
		//为参数赋值
		p->n = i;
		//创建线程
		err = pthread_create(&tid[i], NULL, thr_func, p);
		if(err)
		{
			fprintf(stderr, "create:%s\n", strerror(err));
			exit(1);
		}
	}

	alarm(3);
	
	for(i = 0; i < THRNUM; i++)
	{
		pthread_join(tid[i], &ptr_to_free);
		free(ptr_to_free);
	}

	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond);

	exit(0);
}